package com.herr.springboot.data.mybatisext.controller;

import com.herr.springboot.data.mybatisext.model.User;
import com.herr.springboot.data.mybatisext.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 使用基础mapper自带方法
     */
    @RequestMapping("/selectByPrimaryKey")
    public User selectByPrimaryKey(Integer id){
        return userService.selectByPrimaryKey(id);
    }

    /**
     * mybatis默认开启一级缓存，在sqlsession层级，但mybatis在spring中执行完select，会关闭sqlsession，导致缓存失效
     */
    @RequestMapping("/selectByIdCached2")
    public User selectByIdCached2(Integer id){
        User user = userService.selectByPrimaryKey(id);
        return userService.selectByPrimaryKey(id);
    }

    /**
     * 在事务中，一级缓存会生效，只select了一次
     */
    @RequestMapping("/selectByIdCached")
    @Transactional
    public User selectByIdCached(Integer id){
        User user = userService.selectByPrimaryKey(id);
        return userService.selectByPrimaryKey(id);
    }

    /**
     * UserMapper.xml启用了cache标签，会启用二级缓存。且需要对User进行序列化，否则会报错
     */
    @RequestMapping("/selectById")
    public User selectById(Integer id){
        User user = userService.selectById(id);
        return userService.selectById(id);
    }


    /**
     * 分页
     */
    @GetMapping("/all")
    public Object findAllUser(
            @RequestParam(name = "pageNum", required = false, defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize", required = false, defaultValue = "10") int pageSize) {
        return userService.findAllUser(pageNum,pageSize);
    }

}
